package com.xy.netty.dome.echo;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.CharsetUtil;
import lombok.extern.slf4j.Slf4j;

/**
 * @author niuniu
 */
@Slf4j
public class EchoServerHandler extends ChannelInboundHandlerAdapter {
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        //第一种
        //Channel channel = ctx.channel();
        //channel.writeAndFlush(Unpooled.copiedBuffer("发送信息测试",CharsetUtil.UTF_8));

        //第二种
        //ChannelPipeline channelPipeline = ctx.pipeline();
        //channelPipeline.writeAndFlush(Unpooled.copiedBuffer("发送信息测试",CharsetUtil.UTF_8));
        String sendMsg="服务端发送信息测试";
        ctx.channel().writeAndFlush(Unpooled.copiedBuffer(sendMsg,CharsetUtil.UTF_8));
        log.info("服务端发送数据：{}",sendMsg);
        ByteBuf data = (ByteBuf) msg;
        log.info("服务端收到数据：{}",data.toString(CharsetUtil.UTF_8));
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        log.info("EchoServerHandle channelReadComplete");
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        log.error("EchoServerHandle exceptionCaught",cause);
        ctx.close();
    }


    @Override
    public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
        log.info("EchoServerHandle channelRegistered");
    }

    @Override
    public void channelUnregistered(ChannelHandlerContext ctx) throws Exception {
        log.info("EchoServerHandle channelUnregistered");
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        log.info("EchoServerHandle channelActive");
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        log.info("EchoServerHandle channelInactive");
    }
}
